package com.example.redis.bit;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.redisson.client.RedisClientConfig;
import org.redisson.client.RedisConnection;
import org.redisson.client.codec.StringCodec;
import org.redisson.config.Config;
import org.redisson.config.ConfigSupport;
import org.redisson.connection.ConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * @author Bryan.Zhang
 * @Date 2019-03-20
 */
@Configuration
@ConditionalOnProperty(name = "redis.address")
public class RedisConfiguration {

    private final Logger log = LoggerFactory.getLogger(getClass());

    private final static String REDIS_ADDRESS = "redis.address";
    private final static String REDIS_PASSWORD = "redis.password";
    private final static String REDIS_DBINDEX = "redis.dbindex";
    private final static String REDIS_MASTER_MIN_IDLE_SIZE = "redis.master.min.idle.size";
    private final static String REDIS_MASTER_POOL_SIZE = "redis.master.pool.size";

    @Bean
    public RedissonClient redissonClient(Environment environment){
        log.info("开始redis的自动初始化,地址{}",environment.getProperty(REDIS_ADDRESS));
        Config config = new Config();
        config.setCodec(StringCodec.INSTANCE);
        config.useSingleServer().setAddress(environment.getProperty(REDIS_ADDRESS))
                .setDatabase(Integer.parseInt(environment.getProperty(REDIS_DBINDEX)))
                .setPassword(environment.getProperty(REDIS_PASSWORD))
                .setConnectionPoolSize(Integer.parseInt(environment.getProperty(REDIS_MASTER_POOL_SIZE)))
                .setConnectionMinimumIdleSize(Integer.parseInt(environment.getProperty(REDIS_MASTER_MIN_IDLE_SIZE)));
        RedissonClient redissonClient = Redisson.create(config);
        return redissonClient;
    }

    @Bean
    public RedisConnection redisConnection(Environment environment){
        RedisClientConfig config = new RedisClientConfig();
        config.setAddress(environment.getProperty(REDIS_ADDRESS))
                .setPassword(environment.getProperty(REDIS_PASSWORD))
                .setDatabase(Integer.parseInt(environment.getProperty(REDIS_DBINDEX)))
                .setClientName("redisClient");
        RedisClient redisClient = RedisClient.create(config);
        RedisConnection redisConnection = redisClient.connect();
        return redisConnection;
    }

    @Bean
    public ActInstanceFactory actInstanceFactory(){
        return new ActInstanceFactory();
    }

    @Bean
    public SpringAware springAware(){
        return new SpringAware();
    }
}
